package de.tsystems.jsfdict.beans;

import de.tsystems.jsfdict.api.LanguageService;
import de.tsystems.jsfdict.model.Language;
import de.tsystems.jsfdict.model.Translation;
import de.tsystems.jsfdict.model.Word;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

@Named("languageBean")
@Scope("session")
@Controller
public class LanguageBean implements Serializable {

    @Inject
    @Named("languageService")
    private LanguageService languageService;

    public String name;
    private List<SelectItem> languageItems = new LinkedList<SelectItem>();

    public void setLanguageService(LanguageService languageService) {
        this.languageService = languageService;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String save() {
        Language lng = new Language();
        lng.setName(getName());
        languageService.save(lng);
        clearForm();
        FacesContext context = FacesContext.getCurrentInstance();

        context.addMessage(
                null,
                new FacesMessage(
                        FacesMessage.SEVERITY_INFO,
                        "Successful",
                        String.format("Language '%s' had been added successfully", lng.getName())
                )
        );

        return "";
    }

    private void clearForm() {
        setName("");
        languageItems.clear();
    }

    public List<Language> getLanguages() {
        return languageService.listAll();
    }

    public List<SelectItem> getLanguageItems() {
        if (languageItems.size() < 1) {
            languageItems.add(new SelectItem("", ""));
            for (Language language : getLanguages()) {
                languageItems.add(new SelectItem(language, language.getName()));
            }
        }
        return languageItems;
    }


    public void removeLanguage(Language language) {
        if (language != null) {
            languageService.remove(language);
        }
    }

}
